package com.katesoft.scale4j.agent;

import static com.katesoft.scale4j.agent.args.AgentArgsParser.parseAndValidateOptions;
import static com.katesoft.scale4j.common.lang.RuntimeUtility.VAR_SERVICE_ID;
import static com.katesoft.scale4j.common.lang.RuntimeUtility.gcOnExit;
import static com.katesoft.scale4j.common.utils.StringUtility.isEmpty;
import static com.katesoft.scale4j.log.LogFactory.configure;

import com.katesoft.scale4j.agent.args.AgentOptions;

/**
 * This class is responsible for managing services lifecycle.
 * <p/>
 * It will read appConfiguration.xml file and launch services from this config file.
 * <p/>
 * also this class will export useful functionality through JMX.
 * 
 * @author kate2007
 */
public final class Agent {
   public static final String DEFAULT_LOCATION = "appConfiguration.xml";

   public static void main(String[] args) throws Throwable {
      gcOnExit();
      if (isEmpty(System.getProperty(VAR_SERVICE_ID))) {
         System.setProperty(VAR_SERVICE_ID, "scale4j_agent");
      }
      AgentOptions options = parseAndValidateOptions(args);
      if (options.log4jConfigurationLocation() != null) {
         configure(options.log4jConfigurationLocation().getFile().getCanonicalPath());
      }
      if (options.isKill() || options.isStop()) {
         KillApp killApp = new KillApp();
         killApp.stop(options);
      } else {
         AgentLauncher agentLauncher = new AgentLauncher(options);
         agentLauncher.call();
         agentLauncher.waitFor();
      }
   }

   private Agent() {
   }
}
